package com.maxdu.labs.stt.fragments;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.stt.R;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphUser;
import com.maxdu.labs.stt.activities.CreateTPlanActivity;
import com.maxdu.labs.stt.activities.SeeTPlanWeeklyActivity;
import com.maxdu.labs.stt.constants.Constants;
import com.maxdu.labs.stt.models.TPlan;
import com.maxdu.labs.stt.models.TrainingType;
import com.maxdu.labs.stt.models.UserVSTPlan;
import com.maxdu.labs.stt.models.db.TPlanDBHelper;
import com.maxdu.labs.stt.models.db.UserVSTPlanDBHelper;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;

public class TPlansFragment extends Fragment {
	
	private ListView myTPlansLV;
	private Button addTPlanBtn;
	private ProgressBar loading;
	private String currentUserId = null;
	private TextView noTPlanYet;
	
	private TPlansAdapter adapter;
	
	private List<TPlan> myTPlans;
	
   @Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
	    myTPlans = new ArrayList<TPlan>();
        adapter = new TPlansAdapter(getActivity(), R.layout.row_training_request, myTPlans);
        
        //((MainTestMenuActivity)getActivity()).setActionBarTitle(getString(R.string.tplans));
		
	    Session session = Session.getActiveSession();
	    if (session != null && session.isOpened()) {
	    	
	        // Get the user's data
	        makeMeRequest(session);
	    }
	}

   	@Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
              Bundle savedInstanceState) {
          View view = inflater.inflate(R.layout.frag_tplans, container, false);
          
  		myTPlansLV = (ListView)view.findViewById(R.id.lv_my_tplans);
  		addTPlanBtn = (Button)view.findViewById(R.id.btn_add_tplan);
  		loading = (ProgressBar)view.findViewById(R.id.loading);
  		noTPlanYet = (TextView)view.findViewById(R.id.tv_no_tplan_yet);
          
  		myTPlansLV.setAdapter(adapter);
  		
	    addTPlanBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(),CreateTPlanActivity.class);
				startActivity(intent);
			}
		});
  		
          return view ;
   }

   	private void makeMeRequest(final Session session) {
	    // Make an API call to get user data and define a 
	    // new callback to handle the response.
	    Request request = Request.newMeRequest(session, 
	            new Request.GraphUserCallback() {
	        @Override
	        public void onCompleted(GraphUser user, Response response) {
	            // If the response is successful
	            if (session == Session.getActiveSession()) {
	                if (user != null) {
	                    
	                	currentUserId = user.getId();
	                	
	            	    GetMyTrainingsTask task = new GetMyTrainingsTask();
	            	    task.execute(user.getId());
	                }
	            }
	            if (response.getError() != null) {
	                // Handle errors, will do so later.
	            }
	        }
	    });
	    request.executeAsync();
	} 

   	private class GetMyTrainingsTask extends AsyncTask<String, Void, List<TPlan>> {

	    @Override
		protected void onPreExecute() {
			super.onPreExecute();
			loading.setVisibility(View.VISIBLE);
		}
		
		@Override
	    protected List<TPlan> doInBackground(final String... userIds) {

	    	if (userIds != null){
	    		
	    		//STEP 1:: get the TPlans of this user
	    		ParseQuery<ParseObject> query = ParseQuery.getQuery(UserVSTPlanDBHelper.PARSE_DB_TABLENAME_USERVSTPLAN);
	    		query.whereEqualTo(UserVSTPlanDBHelper.PARSE_DB_FIELD_USERID, userIds[0]);
	    		query.whereEqualTo(UserVSTPlanDBHelper.PARSE_DB_FIELD_ACCEPTED, UserVSTPlan.INVITATION_ACCEPTED);
	    		
	    		query.findInBackground(new FindCallback<ParseObject>() {
	    		    public void done(List<ParseObject> acceptedTPlans, ParseException e) {
	    		        if (e == null) {
	    		        	if (acceptedTPlans != null && acceptedTPlans.size()> 0){
	    		        		//STEP 2 :: for each TPlan (UserVSTPlan object) get the TPlan object (so we have the tplan name)
	    		        		for (final ParseObject userVSTrainingPO : acceptedTPlans){

	    		    	    		ParseQuery<ParseObject> query = ParseQuery.getQuery(TPlanDBHelper.PARSE_DB_TABLENAME_TPLAN);
	    		    	    		query.whereEqualTo(TPlanDBHelper.PARSE_DB_FIELD_TPLANID, userVSTrainingPO.getString(UserVSTPlanDBHelper.PARSE_DB_FIELD_TPLANID));
	    		    	    		
	    		    	    		query.findInBackground(new FindCallback<ParseObject>() {
	    		    	    		    public void done(List<ParseObject> trainings, ParseException e) {
	    		    	    		        if (e == null) {
	    		    	    		        	if (trainings != null && trainings.size()> 0){
	    		    	    		        		for (ParseObject trainingPO : trainings){
	    		    	    		        			TPlan tplan = new TPlan(trainingPO.getString(TPlanDBHelper.PARSE_DB_FIELD_TPLANID),
	    		    	    		        												trainingPO.getString(TPlanDBHelper.PARSE_DB_FIELD_NAME),
	    		    	    		        												trainingPO.getInt(TPlanDBHelper.PARSE_DB_FIELD_TYPE1),
	    		    	    		        												trainingPO.getInt(TPlanDBHelper.PARSE_DB_FIELD_DURATION),
	    		    	    		        												trainingPO.getInt(TPlanDBHelper.PARSE_DB_FIELD_FREQUENCY1));
	    		    	    		        			myTPlans.add(tplan);
	    		    	    		        		}
	    		    	    		        		adapter.notifyDataSetChanged();
	    		    	    		        		loading.setVisibility(View.GONE);
	    		    	    		        	} else if (trainings != null){
	    		    	    		        		Log.d(Constants.LOG_TAG, "we couldn't retrieve the TPlan object for the current UserVSTPlan object with tplanId [" 
	    		    	    		        	 	    		        				+ userVSTrainingPO.getString(UserVSTPlanDBHelper.PARSE_DB_FIELD_TPLANID) + "]. tplans list is NULL");
	    		    	    		        		loading.setVisibility(View.GONE);
	    		    	    		        		noTPlanYet.setVisibility(View.VISIBLE);
	    		    	    		        	}else{
	    		    	    		        		Log.d(Constants.LOG_TAG, "we couldn't retrieve the TPlan object for the current UserVSTPlan object with tplanId [" 
		        	 	    		        				+ userVSTrainingPO.getString(UserVSTPlanDBHelper.PARSE_DB_FIELD_TPLANID) + "]. tplans list is EMPTY");
	    		    	    		        		loading.setVisibility(View.GONE);
	    		    	    		        		noTPlanYet.setVisibility(View.VISIBLE);
	    		    	    		        	}
	    		    	    		        } else {
	    		    	    		            Log.d(Constants.LOG_TAG, "Error: " + e.getMessage());
	    		    	    		        }
	    		    	    		    }
	    		    	    		});
	    		        		}
	    		        		Log.d(Constants.LOG_TAG, "GetMyTrainingsTask::we successfully retrieved [" + myTPlans.size()+"] pending Trainings for the user: " + acceptedTPlans.get(0).getString(UserVSTPlanDBHelper.PARSE_DB_FIELD_USERID));
	    		        		adapter.notifyDataSetChanged();
	    		        		loading.setVisibility(View.GONE);
	    		        		
	    		        	}else if(acceptedTPlans == null){
	    		        		Log.w(Constants.LOG_TAG, "we couldn't retrieve the tplans for the current user ["+ userIds[0] +"]: tplans list is NULL");
	    		        	}else{
	    		        		Log.d(Constants.LOG_TAG, "we couldn't retrieve the tplans for the current user ["+ userIds[0] +"]: tplans list is EMPTY");
	    		        		loading.setVisibility(View.GONE);
	    		        		noTPlanYet.setVisibility(View.VISIBLE);
	    		        		
	    		        	}
	    		        } else {
	    		            Log.d(Constants.LOG_TAG, "Error: " + e.getMessage());
	    		        }
	    		    }
	    		});
	    		
	    		return myTPlans;
	    	}
	    	return null;
	    	
	    }
	}
   	
	private class TPlansAdapter extends ArrayAdapter<TPlan>{

		List<TPlan> tplans;
		
		public TPlansAdapter(Context context, int resource,
				List<TPlan> objects) {
			super(context, resource, objects);
			
			tplans = objects;
		}
		
		@Override
	    public View getView(final int position, View convertView, ViewGroup parent) {
	        View view = convertView;
	        if (view == null) {
	        	LayoutInflater inflater = (LayoutInflater)getContext().getSystemService
	        		      (Context.LAYOUT_INFLATER_SERVICE);
	            view = inflater.inflate(R.layout.row_my_tplans, parent,false);
	        }
	
	        final TPlan tplan = tplans.get(position);
	        
	        ImageView tplanTypeIcon = (ImageView) view.findViewById(R.id.image_tplan_type);
	        TextView tplanNameTV = (TextView) view.findViewById(R.id.tv_tplan_name);
	        LinearLayout layout = (LinearLayout) view.findViewById(R.id.layout_full_row);
	        
	        tplanNameTV.setText(tplan.getName());
	        switch (tplan.getType()) {
				case TrainingType.TYPE_CLIMBING:
					tplanTypeIcon.setImageResource(R.drawable.climbing_icon);
					break;
	
				default:
					tplanTypeIcon.setImageResource(R.drawable.running_icon);
					break;
			}
	        
	        layout.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(getActivity(),SeeTPlanWeeklyActivity.class);
					Log.w(Constants.LOG_TAG,"SeeMyTPlans :: tplanId === " + tplan.getId());
					intent.putExtra("tplan", tplan);
	
					startActivity(intent);
				}
			});
	        
	        return view;
	    }
	}
}